<?php
/**
 * Module for Firstdata E-Commerce Credit Card API
 */
 
define('FIRSTDATA_HOST', 'secure.linkpt.net');
define('FIRSTDATA_PORT', '1129');
define('FIRSTDATA_KEYFILE', '/modules/firstdata-ecommerce/1001271425.pem');

register_function('admin_sidebar', 'firstdata_sidebar');
register_admin_panel('firstdata_ecommerce', CN_DOCUMENT_ROOT.'modules/firstdata-ecommerce/panel.php');

register_filter('form_build_input', 'firstdata_build_input');
register_function('form_display_input', 'firstdata_display_input');
register_filter('form_validate_data', 'firstdata_validate_data');

function firstdata_validate_data($content, $args) {
	global $cndb;
	require CN_DOCUMENT_ROOT.'modules/firstdata-ecommerce/lphp.php';
	
	$field = $args['field'];
	
	if($field->lf_data_type == 'Firstdata Credit Card' && $_REQUEST['firstdata_product_id'] /* Only handle if we got credit card data, which sends only on add form */) {
		echo 'validating data';
		/** Process credit card */
		$lphp = new lphp;

		/** Handles transactions by sending to the firstdata servers */
		
		$order = array();
		
		
		// From Constants
		
		$order['host'] = FIRSTDATA_HOST;
		$order['port'] = FIRSTDATA_PORT;
		$order['keyfile'] = FIRSTDATA_KEYFILE;
		
		// From user configuration
		
		$order['configfile'] = cn_get_option('firstdata_storenum');
		$order['cardnumber'] = $_REQUEST['firstdata_cardnumber'];
		$order['cardexpmonth'] = $_REQUEST['firstdata_cardexpmonth'];
		$order['cardexpyear'] = $_REQUEST['firstdata_cardexpyear'];
		$order['ordertype'] = $_REQUEST['firstdata_ordertype'];
		$order['debugging'] = TRUE;
		$order['verbose'] = TRUE;
		
		// Get the price from the product id
		
		$product = $_REQUEST['firstdata_product_id'];
		$price = $cndb->get_var("SELECT `fdp_price` FROM `firstdata_products` WHERE `fdp_id`='$product'");
		
		$count = $_REQUEST['firstdata_product_count'];
		
		$order['chargetotal'] = $price * $count;
		
		// Calculate tax if applicable
		
		echo 'sending curl';
		// Send information securely to first data
		$result = $lphp->curl_process($order);  # use curl methods
		
		if ($result["r_approved"] != "APPROVED")    // transaction failed, print the reason
		{
			$content['errors'][] = "Status:  $result[r_approved]<br>\nError:  $result[r_error]<br><br>\n";
		}
		else	// success
		{		
			print "Status: $result[r_approved]<br>\n";
			print "Transaction Code: $result[r_code]<br><br>\n";
		}
		
		# if verbose output has been checked,
		# print complete server response to a table
		if ($order['verbose'])
		{
			echo "<table border=1>";
	
			while (list($key, $value) = each($result))
			{
				# print the returned hash 
				echo "<tr>";
				echo "<td>" . htmlspecialchars($key) . "</td>";
				echo "<td><b>" . htmlspecialchars($value) . "</b></td>";
				echo "</tr>";
			}	
				
			echo "</TABLE><br>\n";
		}
	}
	
	return $content;
}

function firstdata_display_input($args) {
	$form_elements = $args;
	if($form_elements['data_type'] == 'Firstdata Credit Card' && count($form_elements['elements']) /* Only display if we got data, which only sends if it's an add form */) :?>
	<fieldset>
		<?=$form_elements['elements']['hidden']?>
		<legend><?=$form_elements['display']?></legend>
		<?=$form_elements['elements']['product_description']?>
		<p>
			<label>Card Number</label>
			<?=$form_elements['elements']['card']?>
		</p>
		<p>
			<label>Expiration</label>
			<?=$form_elements['elements']['expiration']?>
		</p>
	
	</fieldset>
	
	<?php endif;
}

function firstdata_build_input($content, $args) {
	global $cndb;
	$listing = $args['listing'];
	$field = $args['field'];
	if($field->lf_data_type == 'Firstdata Credit Card' && !$listing /* Only on add */) {
		
		$column = $field->lf_column;
		
		$form_elements = array('column'=>$column, 'display'=>$field->lf_display_name, 'data_type'=>$field->lf_data_type, 'elements'=>array());
		
		$form_elements['elements']['hidden'] = '
			<input type="hidden" name="firstdata_ordertype" value="SALE"/>
			<input type="hidden" name="firstdata_product_id" value="1"/>
			<input type="hidden" name="firstdata_product_count" value="1"/>
		';
		$form_elements['elements']['card'] = '<input type="text" class="long-text" id="firstdata_cardnumber" name="firstdata_cardnumber"/>';
		
		ob_start();
		?>
		<select name="firstdata_cardexpmonth">
				<option value="01">Jan</option>
				<option value="02">Feb</option>
				<option value="03">Mar</option>
				<option value="04">Apr</option>
				<option value="05">May</option>
				<option value="06">Jun</option>
				<option value="07">Jul</option>
				<option value="08">Aug</option>
				<option value="09">Sep</option>
				<option value="10">Oct</option>
				<option value="11">Nov</option>
				<option value="12">Dec</option>
			</select>
			<select name="firstdata_cardexpyear">
				<?php $year = date('y');
				$max = $year + 20;
				if($max > 100) $max -= 100;
				for($i = $year; $i < $max ; $i ++) : ?>
				<option value="<?=$i?>"><?=$i?></option>
				<?php endfor;?>
			</select>
		<?php
		$expiration = ob_get_clean();
		$form_elements['elements']['expiration'] = $expiration;

		
		$product = $cndb->get_row("SELECT * FROM `firstdata_products` WHERE `fdp_id`='1'");
		$count = 1;
		
		$form_elements['elements']['product_description'] = '<h2>Product: '.$product->fdp_name.'</h2><h4>'.$count.' unit(s) at $'.$product->fdp_price.' per unit</h4><h3>Total Charge (Pre-Taxes): $'.number_format($count * $product->fdp_price, 2).'</h3>';
		
		
	}
	
	return $form_elements;
	
}

function firstdata_orderform($product, $count = 1) {
	global $cndb;
	$product = $cndb->get_row("SELECT * FROM `firstdata_products` WHERE `fdp_id`='$product'");
	?>
	<form method="post" action="<?=CN_URL?>modules/firstdata-ecommerce/handler.php">
		<input type="hidden" name="firstdata_ordertype" value="SALE"/>
		<input type="hidden" name="firstdata_chargetotal" value="<?=$product->fdp_price?>"/>
		<h1>Order Form</h1>
		<h2>Product: <?=$product->fdp_name?></h2>
		<h4><?=$count?> unit(s) at $<?=$product->fdp_price?> per unit</h4>
		<h3>Total Charge (Pre-Taxes): $<?=number_format($count * $product->fdp_price, 2)?></h3>
		<p>
			<label>Credit Card Number</label>
			<input type="text" class="long-text" id="firstdata_cardnumber" name="firstdata_cardnumber"/>
		</p>
		
		<p>
			<label>Card Expiration</label>
			<select name="firstdata_cardexpmonth">
				<option value="01">Jan</option>
				<option value="02">Feb</option>
				<option value="03">Mar</option>
				<option value="04">Apr</option>
				<option value="05">May</option>
				<option value="06">Jun</option>
				<option value="07">Jul</option>
				<option value="08">Aug</option>
				<option value="09">Sep</option>
				<option value="10">Oct</option>
				<option value="11">Nov</option>
				<option value="12">Dec</option>
			</select>
			<select name="firstdata_cardexpyear">
				<?php $year = date('y');
				$max = $year + 20;
				if($max > 100) $max -= 100;
				for($i = $year; $i < $max ; $i ++) : ?>
				<option value="<?=$i?>"><?=$i?></option>
				<?php endfor;?>
			</select>
		</p>
		<p>
			<input type="submit" value="Submit Order"/>
		</p>
	</form>
	<?php
}

function firstdata_sidebar() {
	?>
	<li><a href="?display=firstdata_ecommerce"><span>Firstdata E-Commerce</span></a></li>
	<?php	

}

?>